//
//  MessageViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/19.
//

#import "MessageViewController.h"
#import "MessageListCell.h"
#import "MessageEmptyView.h"
#import "NewsListManager.h"
#import "NewsListModel.h"
#import "NewsReadManager.h"
#import "NewsClearManager.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UIButton *clearBtn;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)MessageEmptyView *emptyView;
@property(nonatomic,strong)NewsListManager *listManager;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,copy)NSString *totalCount;
@property(nonatomic,strong)UILabel *contentLabel;
@property(nonatomic,strong)NewsReadManager *readManager;
@property(nonatomic,strong)NewsClearManager *clearManager;

@end

@implementation MessageViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NewsListManager *)listManager{
    if(!_listManager){
        _listManager = [[NewsListManager alloc]init];
        _listManager.delegate = self;
    }
    return _listManager;
}

-(NewsReadManager *)readManager{
    if(!_readManager){
        _readManager = [[NewsReadManager alloc]init];
        _readManager.delegate = self;
    }
    return _readManager;
}

-(NewsClearManager *)clearManager{
    if(!_clearManager){
        _clearManager = [[NewsClearManager alloc]init];
        _clearManager.delegate = self;
    }
    return _clearManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    self.totalCount = @"0";
    [self createUI];
    [self loadData];
}

#pragma mark - 获取列表数据
-(void)loadData{
    self.listManager.page = [NSString stringWithFormat:@"%ld", self.page];
    [self.listManager loadData];
}

#pragma mark - 读取消息
-(void)readMsgWithId:(NSString*)idstr andRow:(NSInteger)row{
    self.readManager.idStr = idstr;
    self.readManager.row = row;
    [self.readManager loadData];
}

#pragma mark - 清除消息
-(void)clearMsg{
    [self.clearManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"消息中心"];
    
    self.clearBtn = [[UIButton alloc]init];
    [self.clearBtn setImage:[UIImage imageNamed:@"message_clear"] forState:UIControlStateNormal];
    [self.clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:self.clearBtn];
    [self.clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@34);
        make.right.mas_equalTo(@-9);
        make.bottom.mas_equalTo(@-5);
    }];
    self.clearBtn.hidden = YES;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"MessageListCell") forCellReuseIdentifier:@"MessageListCell"];
    [self.view addSubview:self.tableView];
    
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        self_weak_.page = 1;
        [self_weak_ loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self_weak_.page++;
        [self_weak_ loadData];
    }];
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.currentAvailableWidth,10)];
    headView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tableView.tableHeaderView = headView;
    
    self.tableView.hidden = YES;
    
    self.emptyView = [[MessageEmptyView alloc]initWithFrame:CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT)];
    self.emptyView.currentAvailableWidth = self.currentAvailableWidth;
    self.emptyView.currentAvailableHeight = self.currentAvailableHeight;
    [self.view addSubview:self.emptyView];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        self.tableView.frame = CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.currentAvailableWidth,10)];
        headView.backgroundColor = UIColorHex(0xF2F7F6);
        self.tableView.tableHeaderView = headView;
        [self.tableView reloadData];
        self.emptyView.frame = CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
        self.emptyView.currentAvailableWidth = self.currentAvailableWidth;
        self.emptyView.currentAvailableHeight = self.currentAvailableHeight;
        [self.emptyView refreshWidth];
            
        });
    }
}

#pragma mark - 刷新
-(void)refreshWithIsEmpty{
    if(self.dataArr.count > 0){
        self.tableView.hidden = NO;
        self.emptyView.hidden = YES;
        self.clearBtn.hidden = NO;
        self.customNavigationBar.backgroundColor = UIColorHex(0xF2F7F6);
        self.view.backgroundColor = UIColorHex(0xF2F7F6);
        if(self.totalCount.integerValue > 999){
            [self.customNavigationBar setTitle:@"消息中心 999+"];
        }else{
            [self.customNavigationBar setTitle:[NSString stringWithFormat:@"消息中心 %@",self.totalCount]];
        }
    }else{
        self.tableView.hidden = YES;
        self.emptyView.hidden = NO;
        self.clearBtn.hidden = YES;
        self.customNavigationBar.backgroundColor = [UIColor whiteColor];
        self.view.backgroundColor = [UIColor whiteColor];
        [self.customNavigationBar setTitle:@"消息中心"];
    }
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    if(self.dataArr.count == self.totalCount.integerValue){
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - 清理
-(void)clearBtnClick{
    if(self.dataArr.count > 0){
        [self clearMsg];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageListCell"];
    if(indexPath.row < self.dataArr.count){
        NewsListModel *model = self.dataArr[indexPath.row];
        cell.model = model;
    }
    return cell;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        NewsListModel *model = self.dataArr[indexPath.row];
        if(!self.contentLabel){
            self.contentLabel = [[UILabel alloc]init];
            self.contentLabel.font = JPUIFontPingFangSCRegular(14);
            self.contentLabel.textColor = KFontGrayColor;
            self.contentLabel.numberOfLines = 0;
        }
        self.contentLabel.text = model.content;
        CGSize size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-32-48-10, MAXFLOAT)];
        CGFloat total_h = 84+size.height;
        return total_h;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        NewsListModel *model = self.dataArr[indexPath.row];
        if([model.isRead isEqualToString:@"0"]){
            //未读消息点了可以读取
            [self readMsgWithId:model._id andRow:indexPath.row];
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.listManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [NewsListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"list"]];
        [self.dataArr addObjectsFromArray:arr];
        self.totalCount = [NSString stringWithFormat:@"%@",dic[@"data"][@"count"]];
        if(self.page == 1){
            [self refreshWithIsEmpty];
        }else{
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            if(self.dataArr.count == self.totalCount.integerValue){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }
    }
    
    if([manager isEqual:self.readManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        NewsListModel *model = [NewsListModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.readManager.row < self.dataArr.count){
            [self.dataArr replaceObjectAtIndex:self.readManager.row withObject:model];
        }
        [self.tableView reloadData];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"messageUpdate" object:nil];
    }
    
    if([manager isEqual:self.clearManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        self.page = 1;
        [self.dataArr removeAllObjects];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"messageClear" object:nil];
        [self refreshWithIsEmpty];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.listManager]){
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

@end
